<?php
namespace Backend\Models\Member;

use Backend\Library\Helper;
use Backend\Models\Base;
use think\exception\PDOException;

/**
 * Class Sign
 * @package Backend\Models\Member
 */
class Sign extends Base
{
    public function initialize()
    {
        parent::initialize();
    }

    public function getSource()
    {
        return 'member_sign';
    }

    /**
     * @param $where
     * @param $limit
     * @param $offset
     *
     * @return bool
     */
    public function gets($where, $limit, $offset)
    {
        $query = $this->queryBuilder()->columns('*')->from(self::class);
        if (is_array($where) && count($where) > 0) {
            if (isset($where['uid'])) {
                $query->andWhere('uid=:uid:', ['uid' => intval($where['uid'])]);
            }
            if (isset($where['start_time'])) {
                $query->andWhere('create_at >=:start: ', ['start' => Helper::getDatepickerDateToStandardDate($where['start_time'])]);
            }
            if (isset($where['end_time'])) {
                $query->andWhere('create_at <=:end: ', ['end' => Helper::getDatepickerDateToStandardDate($where['end_time'])]);
            }
        }
        try {
            $ret = $query->orderBy('id DESC')->limit($limit, $offset)->getQuery()->execute();
            if ($ret !== false) {
                return $ret->toArray();
            }
        } catch (\PDOException $ex) {
            $this->errorLog('SELECT', $query->getPhql(), $ex->getMessage(), __FILE__, __LINE__);
        }
        return false;
    }

    /**
     * @param $where
     *
     * @return bool
     */
    public function getCount($where)
    {
        $query = $this->queryBuilder()->columns('COUNT(0) AS cnt')->from(self::class);
        if (is_array($where) && count($where) > 0) {
            if (isset($where['uid'])) {
                $query->andWhere('uid=:uid:', ['uid' => intval($where['uid'])]);
            }
            if (isset($where['start_time'])) {
                $query->andWhere('create_at >=:start: ', ['start' => Helper::getDatepickerDateToStandardDate($where['start_time'])]);
            }
            if (isset($where['end_time'])) {
                $query->andWhere('create_at <=:end: ', ['end' => Helper::getDatepickerDateToStandardDate($where['end_time'])]);
            }
        }
        try {
            $ret = $query->getQuery()->execute()->toArray();
            if ($ret !== false) {
                return $ret[0]['cnt'];
            }
        } catch (\PDOException $ex) {
            $this->errorLog('SELECT', $query->getPhql(), $ex->getMessage(), __FILE__, __LINE__);
        }
        return false;
    }
}
